<template>
	<view class="page-body pbox pt50">
		<u-form :model="model" ref="uForm" :errorType="errorType" class="block " v-if="showCanvas == false">
			<u-steps :list="numList" :icon="icon" mode="number" :current="current"></u-steps>
			<view class="mt60"></view>
			<view v-if="current==0">
				<view v-if="urlShareToken == ''">
					<u-form-item :rightIconStyle="{color: '#888', fontSize: '32rpx'}" :label-position="labelPosition" label="邀请人手机"
					 prop="shareMobile" label-width="150">
						<u-input :border="border" placeholder="请输入手机号" v-model="model.shareMobile" type="number"></u-input>
						<u-button slot="right" type="success" size="medium" @click="getShareInfo">查询</u-button>
					</u-form-item>
					<u-form-item :label-position="labelPosition" label="图形验证码" prop="verifyCode" label-width="150">
						<view class="smll">
							<view class="flex_bd">
								<u-input :border="border" placeholder="输入图形验证码" v-model="model.verifyCode" type="number"></u-input>
							</view>
							<u-image width="200rpx" height="80rpx" :src="verifyUrl" @click="changeVerifyUrl"></u-image>
						</view>
					</u-form-item>
				</view>
				<view v-if="shareUserInfo.real_name">
					<view class="mt30"><text>邀请人姓名：</text>{{shareUserInfo.real_name}}</view>
					<view class="mt30"><text>邀请人手机：</text>{{shareUserInfo.mobile}}</view>
					<view class="mt30"><text>邀请人级别：</text>{{shareUserInfo.proxy_name}}</view>
					<text class="block fs32 mt30 red">* 请核实上级信息，提交后将不可改变</text>
				</view>
				<view v-if="shareErrorTip">
					<text class="block fs32 mt30 red text-center" style="line-height: 200rpx;">{{shareErrorTip}}</text>
				</view>
				<u-button size="default" shape="circle" type="primary" class="block mt40" @click="submitByCheckShare">下一步</u-button>
			</view>
			<view v-if="current==1">
				<u-form-item :rightIconStyle="{color: '#888', fontSize: '32rpx'}" right-icon="phone" :label-position="labelPosition"
				 label="手机号码" prop="mobile" label-width="150">
					<u-input :border="border" placeholder="请输入手机号" v-model="model.mobile" type="number"></u-input>
				</u-form-item>
				<u-form-item :label-position="labelPosition" label="验证码" prop="code" label-width="150">
					<u-input :border="border" placeholder="请输入验证码" v-model="model.code" type="text"></u-input>
					<u-button slot="right" type="success" size="mini" @click="getCode">{{codeTips}}</u-button>
				</u-form-item>
				<u-button size="default" shape="circle" type="primary" class="block mt40 flex_bd" @click="submitByCheckMobile">下一步</u-button>
				<view class="mt20 text-center" @click="current--"><u-icon name="arrow-left"  size="28"></u-icon>返回</view>
				<u-verification-code seconds="60" ref="uCode" @change="codeChange"></u-verification-code>
			</view>
			<view v-if="current==2">
				<text class=" fs32 font-w700 mt20 red" :style="{display: this.user_exist==1 ? 'block' : 'none'}">1、您的手机已在商城注册将关联信息<br>2、默认使用商城密码登录</text>
				<text class="block fs32 mt20">请选择您的意向代理身份，提交后将不可改变</text>
				<view @click="selectRroxyShow = true">
				<u-form-item :label-position="labelPosition" label="代理身份" prop="proxy_name" label-width="150">
					<u-input :border="border" type="select" :select-open="selectRroxyShow" v-model="model.proxy_name" placeholder="请选择代理身份" @click="selectRroxyShow = true" ></u-input>
				</u-form-item>
				</view>
				<u-form-item :leftIconStyle="{color: '#888', fontSize: '32rpx'}" class="mt20" right-icon="account" label-width="150"
				 :label-position="labelPosition" label="真实姓名" prop="real_name">
					<u-input :border="border" placeholder="请输入真实姓名" v-model="model.real_name" type="text"></u-input>
				</u-form-item>
				<view class="block fs32  mt20 red" :style="{display: this.set_password==1 ? 'block' : 'none'}">
					<u-form-item :label-position="labelPosition" label="登录密码" prop="password" label-width="150">
						<u-input :password-icon="true" :border="border" type="password" v-model="model.password" placeholder="请输入密码"></u-input>
					</u-form-item>
					<u-form-item :label-position="labelPosition" label="确认密码" label-width="150" prop="rePassword">
						<u-input :border="border" type="password" v-model="model.rePassword" placeholder="请确认密码"></u-input>
					</u-form-item>
				</view>
				<u-button size="default" shape="circle" type="primary" class="block mt40" @click="submitByInfo">下一步</u-button>
				<view class="mt20 text-center" @click="current--"><u-icon name="arrow-left"  size="28"></u-icon>返回</view>
				<u-select mode="single-column" :list="proxyInvitelist" :default-value="proxyLevelDefaultValue" v-model="selectRroxyShow"
				 @confirm="proxyLevelConfirm"></u-select>
			</view>
			<view v-if="current==3" >
				<text class="block text-center font-w700 fs42 mt20">代理协议</text>
				<rich-text :nodes="channel_protocol"></rich-text>
				<view style="height: 100px;"></view>
				<view class="signatureBtn">
					<u-button size="default" shape="circle" type="success" class="mt40" @click="createCanvas">我已阅读并同意本协议，签名提交</u-button>
					<view class="mt20 text-center" @click="current--"><u-icon name="arrow-left"  size="28"></u-icon>返回</view>
				</view>
				
			</view>
			<view v-if="current==4">
				<view class="top_tip_icon">
					<u-image width="100%" height="100%" src="/pagesB/static/channel/images/icon01.png" shape="circle"></u-image>
				</view>
				<text class="block font-w700 fs42 mt20 text-center">注册成功</text>
				<text class="block fs32 mt20 mb40 text-center">登陆后完成任务正式成为代理</text>
				<u-button size="default" shape="circle" type="primary"  @click="app.goPage('login')">返回登陆</u-button>
			</view>
		</u-form>
		<view class="signature" v-if="showCanvas==true" @touchmove.stop.prevent="">
			<text class="block fs32 clearfix max-width" style="background-color: #FFFFFF;">请在下面灰色位置签名</text>
			<canvas class="mycanvas " canvas-id="mycanvas" @touchstart="touchstart" @touchmove="touchmove" @touchend="touchend"></canvas>
			<view class="footer">
				<u-button size="medium" shape="circle" type="warning" @click="clear">清除</u-button>
				<u-button size="medium" shape="circle" type="primary" :loading="isLoading" @click="finish">提交</u-button>
				<u-button size="medium" shape="circle" @click="close">关闭</u-button>
			</view>
		</view>
	</view>
</template>

<script>
	var x = 20;
	var y = 20;
	export default {
		data() {
			let that = this;
			return {
				showCanvas: false,
				ctx: '', //绘图图像
				points: [], //路径点集合 
				isLoading: false,
				current: 0, //当前步数
				shareUserInfo: {
				}, //邀请人信息
				urlShareToken:'',//链接的邀请码
				verifyUrl: '',
				shareErrorTip: '',
				model: {
					shareMobile: '', //邀请人手机
					verifyCode:'',
					mobile: '',
					code: '',
					proxy_id: 0,
					proxy_name: '',
					real_name: '',
					password: '',
					rePassword:'',
					share_token: '',
					signature: '', //签名图片
				},
				numList: [{
					name: '邀请信息'
				}, {
					name: '验证手机'
				}, {
					name: '信息登记'
				}, {
					name: '签约信息'
				}, {
					name: '注册完成'
				}, ],
				icon: 'map-fill',
				user_exist: 0,//是否存在商城会员
				set_password:1,//是否需要设置密码
				proxyLevelDefaultValue: [0],
				proxyInvitelist: [], //可升级代理列表
				rulesShareMobile: {
					shareMobile: [{
							required: true,
							message: '请输入邀请手机号',
							trigger: ['change', 'blur'],
						},
						{
							validator: (rule, value, callback) => {
								// 调用uView自带的js验证规则，详见：https://www.uviewui.com/js/test.html
								return this.$u.test.mobile(value);
							},
							message: '手机号码不正确',
							// 触发器可以同时用blur和change，二者之间用英文逗号隔开
							trigger: ['change', 'blur'],
						}
					],
					verifyCode: [{
						required: true,
						message: '请输入验证码',
						trigger: ['change', 'blur'],
					}]
				},
				rulesgetCode:{
					mobile: [{
							required: true,
							message: '请输入手机号',
							trigger: ['change', 'blur'],
						},
						{
							validator: (rule, value, callback) => {
								// 调用uView自带的js验证规则，详见：https://www.uviewui.com/js/test.html
								return this.$u.test.mobile(value);
							},
							message: '手机号码不正确',
							// 触发器可以同时用blur和change，二者之间用英文逗号隔开
							trigger: ['change', 'blur'],
						}
					]
				},
				rulesCheckMobile: {
					mobile: [{
							required: true,
							message: '请输入手机号',
							trigger: ['change', 'blur'],
						},
						{
							validator: (rule, value, callback) => {
								// 调用uView自带的js验证规则，详见：https://www.uviewui.com/js/test.html
								return this.$u.test.mobile(value);
							},
							message: '手机号码不正确',
							// 触发器可以同时用blur和change，二者之间用英文逗号隔开
							trigger: ['change', 'blur'],
						}
					],
					code: [{
							min: 6,
							required: true,
							message: '请输入6位验证码',
							trigger: ['change', 'blur'],
						},
						{
							type: 'number',
							message: '验证码只能为数字',
							trigger: ['change', 'blur'],
						}
					]
				},
				rulesInfo: {
					proxy_name: [{
						required: true,
						message: '请选择代理身份',
						trigger: 'blur',
					}, ],
					real_name: [{
							required: true,
							message: '请输入真实姓名',
							trigger: 'blur',
						},
						{
							min: 2,
							max: 15,
							message: '姓名长度在2到15个字符',
							trigger: ['change', 'blur'],
						},
						{
							// 此为同步验证，可以直接返回true或者false，如果是异步验证，稍微不同，见下方说明
							validator: (rule, value, callback) => {
								// 调用uView自带的js验证规则，详见：https://www.uviewui.com/js/test.html
								return this.$u.test.chinese(value);
							},
							message: '姓名必须为中文',
							// 触发器可以同时用blur和change，二者之间用英文逗号隔开
							trigger: ['change', 'blur'],
						}
					],
					password: [{
							required: true,
							message: '请输入密码',
							trigger: ['change', 'blur'],
						},
						{
							min: 8,
							message: '密码不能少于8个字符',
							trigger: 'change',
						}
					],
					rePassword: [{
							required: true,
							message: '请重新输入密码',
							trigger: ['change', 'blur'],
						},
						{
							validator: (rule, value, callback) => {
								return value === this.model.password;
							},
							message: '两次输入的密码不相等',
							trigger: ['change', 'blur'],
						}
					],
				},
				border: false,
				check: false,
				labelPosition: 'left',
				codeTips: '',
				errorType: ['toast'],
				channel_protocol: '', //代理协议
				showHeight: 200,
				toggle: false,
				isShow: false,
				selectRroxyShow: false,
			}
		},
		onLoad(options) {
			var setting = uni.getStorageSync("setting");
			this.channel_protocol = setting.channel_protocol;
			this.model.proxy_id = options.proxy_id;
			if (typeof(options.share_token) != 'undefined' && options.share_token !='') {
				this.urlShareToken = options.share_token;
				this.getShareInfo(options.share_token);
			}
			this.verifyUrl = this.config.baseUrl + '/index.php/publics/api.index/verify/session_id/'+uni.getStorageSync("session_id");
		},
		computed: {
			borderCurrent() {
				return this.border ? 0 : 1;
			},
		},
		onReady() {},
		methods: {
			getShareInfo(share_token = '') {
				var data = {};
				var is_ok = false;
				data.proxy_id = this.model.proxy_id;
				if (share_token != '') {
					data.share_token = share_token;
					is_ok = true;
				} else {
					this.$refs.uForm.validate(valid => {
						if (!valid) {
							return false;
						}
						is_ok = true;
						data.shareMobile = this.model.shareMobile;
						data.verifyCode = this.model.verifyCode;
					});
					
				}
				if (is_ok == false) {
					return false;
				}
				this.model.share_token = '';
				this.shareErrorTip = '';
				//请求api
				this.$u.get('channel/api.passport/searchShareUser', data).then(res => {
					this.changeVerifyUrl();
					this.verifyCode = '';
					if (res.code < 0) {
						this.shareErrorTip = res.msg;
						return false;
					}
					this.model.share_token = res.data.share_token;
					this.proxyInvitelist = res.data.proxyInvitelist;
					if (this.model.proxy_id  > 0){
						this.model.proxy_name = this.proxyInvitelist[0]['label'];
					}
					delete res.data.share_token;
					delete res.data.proxyInvitelist;
					this.shareUserInfo = res.data;
				}).catch(res=>{
					this.changeVerifyUrl();
				})
			},
			changeVerifyUrl() {
				if (this.verifyUrl.indexOf('rand=') > -1) {
					this.verifyUrl = this.verifyUrl.substr(0, this.verifyUrl.length - 19);
				}
				this.verifyUrl += '?rand=' + new Date().getTime();
			},
			submitByCheckShare() {
				if (this.model.share_token == '') {
					this.$u.toast('请核实上级后再操作.');
					return false;
				}
				this.current = 1;
			},
			submitByCheckMobile() {
				this.$refs.uForm.setRules(this.rulesCheckMobile);
				this.$refs.uForm.validate(valid => {
					if (!valid) {
						return false;
					}
					//验证手机验证码
					this.$u.get('channel/api.passport/checkMobile', {
						'type': 'channel_sms_register',
						'mobile': this.model.mobile,
						'code': this.model.code
					}).then(res => {
						this.user_exist = res.data.user_exist;
						this.set_password  = res.data.set_password;
						this.model.real_name = res.data.real_name;
						this.current = 2;
					})

				});
			},
			submitByInfo() {
				var rules = this.rulesInfo;
				if (this.set_password == 0) { //不需要设置密码执行
					delete rules.password;
					delete rules.rePassword;
				}
				this.$refs.uForm.setRules(this.rulesInfo);
				this.$refs.uForm.validate(valid => {
					if (valid) {
						this.current = 3;
						var setting = uni.getStorageSync("setting");
						this.channel_protocol = setting.channel_protocol;
					} else {
						console.log('验证失败');
					}
				});
			},
			codeChange(text) {
				this.codeTips = text;
			},
			// 获取验证码
			getCode() {
				if (this.$refs.uCode.canGetCode) {
					this.$refs.uForm.setRules(this.rulesgetCode);
					this.$refs.uForm.validate(valid => {
						if (valid) {
							// 向后端请求验证码
							uni.showLoading({
								title: '正在获取验证码',
								mask: true
							})
							this.$u.get('publics/api.sms/sendCode', {
								'type': 'channel_sms_register',
								'mobile': this.model.mobile
							}).then(res => {
								uni.hideLoading();
								// 这里此提示会被this.start()方法中的提示覆盖
								this.$u.toast('验证码已发送');
								this.user_exist = res.data.user_exist;
								// 通知验证码组件内部开始倒计时
								this.$refs.uCode.start();
							})
						}
					});

				} else {
					this.$u.toast('倒计时结束后再发送');
				}
			},
			// 选择申请代理层级回调
			proxyLevelConfirm(e) {
				this.model.proxy_id = 0;
				this.model.proxy_name = 0;
				e.map((val, index) => {
					this.model.proxy_name = val.label;
					this.model.proxy_id = val.value;
					//同步默认选项
					for (var i = 0; i < this.proxyInvitelist.length; i++) {
						if (this.proxyInvitelist[i].value == val.value) {
							this.proxyLevelDefaultValue = [i];
							break;
						}
					}
				})
			},
			//提交注册
			 finish() {
				if (this.isLoading == true) {
					return true;
				}
				this.isLoading = true;
				let that = this;
				uni.showLoading();
				uni.canvasToTempFilePath({
					canvasId: 'mycanvas',
					success: function(res) {
						
						//#ifdef APP-PLUS 
						 that.app.appReadFileToBase64(res.tempFilePath,res=>{
							that.model.signature = res
							that.post();
						});
						return true;
						//#endif
						//#ifdef MP-WEIXIN
						that.app.wxmpReadFileToBase64(res.tempFilePath,res=>{
							that.model.signature = res
							that.post();
						});
						return true;
						//#endif
						that.model.signature = res.tempFilePath;
						that.post();
					},
					fail: function() {
						that.isLoading = false;
					}
				})
			},
			post(){
				this.$u.post('channel/api.passport/register', this.model).then(res => {
					uni.hideLoading();
					this.isLoading = false;
					this.showCanvas = false;
					this.current = 4;
				}).catch(res=>{
					this.isLoading = false;
				})
			},
			//关闭并清空画布
			close: function() {
				this.isPost = false;
				this.showCanvas = false;
				this.clear();
			},
			//创建并显示画布
			createCanvas: function() {
				this.showCanvas = true;
				this.ctx = uni.createCanvasContext("mycanvas", this); //创建绘图对象
				//设置画笔样式
				this.ctx.lineWidth = 4;
				this.ctx.lineCap = "round"
				this.ctx.lineJoin = "round"
			},
			//触摸开始，获取到起点
			touchstart: function(e) {
				let startX = e.changedTouches[0].x;
				let startY = e.changedTouches[0].y;
				let startPoint = {
					X: startX,
					Y: startY
				};
				this.points.push(startPoint);
				//每次触摸开始，开启新的路径
				this.ctx.beginPath();
			},
			//触摸移动，获取到路径点
			touchmove: function(e) {
				let moveX = e.changedTouches[0].x;
				let moveY = e.changedTouches[0].y;
				let movePoint = {
					X: moveX,
					Y: moveY
				};
				this.points.push(movePoint); //存点
				let len = this.points.length;
				if (len >= 2) {
					this.draw(); //绘制路径
				}
			},
			// 触摸结束，将未绘制的点清空防止对后续路径产生干扰
			touchend: function() {
				this.points = [];
			},
			/* ***********************************************
			#   绘制笔迹
			#	1.为保证笔迹实时显示，必须在移动的同时绘制笔迹
			#	2.为保证笔迹连续，每次从路径集合中区两个点作为起点（moveTo）和终点(lineTo)
			#	3.将上一次的终点作为下一次绘制的起点（即清除第一个点）
			************************************************ */
			draw: function() {
				let point1 = this.points[0]
				let point2 = this.points[1]
				this.points.shift()
				this.ctx.moveTo(point1.X, point1.Y)
				this.ctx.lineTo(point2.X, point2.Y)
				this.ctx.stroke()
				this.ctx.draw(true)
			},
			//清空画布
			clear: function() {
				let that = this;
				this.isPost = false;
				uni.getSystemInfo({
					success: function(res) {
						let canvasw = res.windowWidth;
						let canvash = res.windowHeight;
						that.ctx.clearRect(0, 0, canvasw, canvash);
						that.ctx.draw(true);
					},
				})
			},

		}
	}
</script>

<style lang="scss">
	page {
		background: #fff;
	}
	
	.top_tip_icon {
		width: 150rpx !important;
		height: 150rpx !important;
		margin: 0rpx auto;
	}

	.protocolBox {
		padding-bottom: 120rpx;
	}

	.signatureBtn {
		width: 93%;
		position: fixed;
		bottom: 0rpx;
		padding-bottom: 30rpx;
		background-color: #FFFFFF;
	}

	.signature {
		z-index: 999;
		width: 100%;
	}

	

	.title {
		height: 50upx;
		line-height: 50upx;
		font-size: 16px;
	}

	.mycanvas {
		width: 100%;
		height: calc(100vh - 220upx);
		background-color: #ECECEC;
	}

	.footer {
		font-size: 14px;
		height: 150upx;
		display: flex;
		position: fixed;
		bottom: 0rpx;
		left: 0rpx;
		width: 100%;
		justify-content: space-around;
		align-items: center;
		background-color: #FFFFFF;
	}

	.left,
	.right,
	.close {
		line-height: 100upx;
		height: 100upx;
		width: 220upx;
		text-align: center;
		font-weight: bold;
		color: white;
		border-radius: 5upx;
	}

	.left {
		background: #007AFF;
	}

	.right {
		background: orange;
	}

	.close {
		background: #A3A3A3;
	}

</style>
